package com.kasax.plugin.app.visitor

import com.kasax.plugin.app.LogUtils
import com.kasax.plugin.app.visitor.lifecycle2.LifecycleOnCreateMethodVisitor2
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes

class LifecycleClassVisitor extends ClassVisitor implements Opcodes {
    String mClsName
    String TAG = "LifecycleClassVisitor"

    LifecycleClassVisitor(ClassVisitor cv) {
        super(Opcodes.ASM7, cv)
    }

    @Override
    void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        LogUtils.d(TAG, "visit started: $name")
        this.mClsName = name
        super.visit(version, access, name, signature, superName, interfaces)
    }

    @Override
    MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        LogUtils.d(TAG, "visitMethod : $name")
        MethodVisitor mv = cv.visitMethod(access, name, descriptor, signature, exceptions)
        // 确保所有方法都有返回
        if (mv == null) {
            return null
        }

        // 匹配FragmentActivity或AppCompatActivity及其子类
        if (this.mClsName != null && (this.mClsName.equals("android/support/v4/app/FragmentActivity") || 
            this.mClsName.equals("androidx.appcompat.app.AppCompatActivity") || 
            this.mClsName.startsWith("com/kasax/"))) {
            if ("onCreate".equals(name)) {
                LogUtils.d(TAG, "visitMethod : $name , exec LifecycleOnCreateMethodVisitor2")
                // 处理onCreate方法
                return new LifecycleOnCreateMethodVisitor2(mv)
            }
        }

        // 默认返回原始MethodVisitor
        return mv
    }

    @Override
    void visitEnd() {
        LogUtils.d(TAG, "visit end")
        super.visitEnd()
    }
}